package com.huang.gulimail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huang.common.utils.PageUtils;
import com.huang.common.utils.Query;

import com.huang.gulimail.product.dao.CategoryDao;
import com.huang.gulimail.product.entity.CategoryEntity;
import com.huang.gulimail.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 使用redis缓存
     * 1.空结果缓存：解决缓存穿透
     * 2.设置过期时间（加随机值）：解决缓存雪崩
     * 3.加锁：解决缓存击穿
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //使用json存储
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if(StringUtils.isEmpty(catelogJson)){
        List<CategoryEntity> categoryEntities = listWithTreex();
            return categoryEntities;
        }else {
            List<CategoryEntity> categoryEntities = JSON.parseObject(catelogJson, new TypeReference<List<CategoryEntity>>() {
            });
            return categoryEntities;
        }
    }


    public List<CategoryEntity> listWithTreex() {
        //本地锁方法
        //redis枷锁，加了所之后为了防止上一个请求申请sql数据set到redis，判断缓存是否有，如果有就不执行
        synchronized (this) {
            String catelogJson = redisTemplate.opsForValue().get("catelogJson");
            if(StringUtils.isEmpty(catelogJson)){
                List<CategoryEntity> categoryEntities = JSON.parseObject(catelogJson, new TypeReference<List<CategoryEntity>>() {
                });
                return categoryEntities;
            }
            List<CategoryEntity> entities = baseMapper.selectList(null);
//important
            List<CategoryEntity> level1Meus = entities.stream().filter(categoryEntity ->
                    categoryEntity.getParentCid() == 0
            ).map(meus -> {
                meus.setChildren(getChildren(meus, entities));
                return meus;
            }).sorted((meus1, meus2) -> {
                return (meus1.getSort() == null ? 0 : meus1.getSort()) - (meus2.getSort() == null ? 0 : meus2.getSort());
            }).collect(Collectors.toList());
            //1.空结果缓存：解决缓存穿透
            //redisTemplate.opsForValue().set("catelogJson",0);
            String s = JSON.toJSONString(level1Meus);
            //2.设置过期时间（加随机值）：解决缓存雪崩
            redisTemplate.opsForValue().set("catelogJson",s,1, TimeUnit.DAYS);
            //一定要把缓存设在同步代码块里面
            return level1Meus;

        }
    }

    @Override
    public void removeMeusByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long>paths=new ArrayList<>();
        List<Long> ppath=findParentPath(catelogId,paths);
        return ppath.toArray(new Long[ppath.size()]);
    }
    private List<Long>findParentPath(Long catelogId,List<Long>paths){
        CategoryEntity byId=this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        paths.add(catelogId);
        return paths;
    }

    private List<CategoryEntity>getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
             categoryEntity.setChildren(getChildren(categoryEntity,all));
            return categoryEntity;
        }).sorted((meus1,meus2)->{
            return (meus1.getSort()==null?0:meus1.getSort())-(meus2.getSort()==null?0:meus2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

//    /**
//     * 从数据库查询并封装数据::分布式锁
//     * @return
//     */
//    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
//
//        //1、占分布式锁。去redis占坑      设置过期时间必须和加锁是同步的，保证原子性（避免死锁）
//        String uuid = UUID.randomUUID().toString();
//        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
//        if (lock) {
//            System.out.println("获取分布式锁成功...");
//            Map<String, List<Catelog2Vo>> dataFromDb = null;
//            try {
//                //加锁成功...执行业务
//                dataFromDb = getDataFromDb();
//            } finally {
//                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//
//                //删除锁
//                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
//
//            }
//            //先去redis查询下保证当前的锁是自己的
//            //获取值对比，对比成功删除=原子性 lua脚本解锁
//            // String lockValue = stringRedisTemplate.opsForValue().get("lock");
//            // if (uuid.equals(lockValue)) {
//            //     //删除我自己的锁
//            //     stringRedisTemplate.delete("lock");
//            // }
//
//            return dataFromDb;
//        } else {
//            System.out.println("获取分布式锁失败...等待重试...");
//            //加锁失败...重试机制
//            //休眠一百毫秒
//            try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
//            return getCatalogJsonFromDbWithRedisLock();     //自旋的方式
//        }
//    }

}